﻿using Abp.AspNetCore.Configuration;
using Abp.AspNetCore.Mvc.ExceptionHandling;
using Abp.Dependency;
using Abp.Runtime.Validation;
using Abp.Web.Models;
using Castle.Core.Logging;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Partner.Utility;

namespace HCD.Web
{
    public class ExceptionResultFilter : AbpExceptionFilter
    {
        public ExceptionResultFilter(IErrorInfoBuilder errorInfoBuilder, IAbpAspNetCoreConfiguration configuration) 
            : base(errorInfoBuilder, configuration)
        {
        }

        protected override void HandleAndWrapException(ExceptionContext context, WrapResultAttribute wrapResultAttribute)
        {
            BaseBizResult re = new BaseBizResult() { Success = false };
            if (context.Exception is BizException)
            {
                var ex = context.Exception;
                re.Message = ex.Message;
                re.ErrorCode = (ex as BizException).ErrorCode;
                re.ErrorData = (ex as BizException).ErrorData;
            }
            else if (context.Exception.InnerException is BizException)
            {
                var ex = context.Exception.InnerException;
                re.Message = ex.Message;
                re.ErrorCode = (ex as BizException).ErrorCode;
                re.ErrorData = (ex as BizException).ErrorData;
            }
            else
            {
                var ex = context.Exception;
                Logger.Error(ex.Message, ex);
#if DEBUG
                re.Message = string.Format("{0}{1}", ex.Message, ex.ToString());
#else
                  re.Message = "系统开了一点小差";
#endif
            }
            context.Result = new ObjectResult(re);
        }
    }
}
